package thread;

import java.security.PrivilegedAction;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * @author weim
 * @date 18-8-30
 */
public class MyThread {

    public static void main(String[] args) {

        System.out.println("main start");

        //one way
        OneWay oneWay = new OneWay();
        oneWay.start();

        //two way
        TwoWay twoWay = new TwoWay();
        new Thread(twoWay).start();

        //three way
        try {
            ThreeWay threeWay = new ThreeWay();

            FutureTask<String> task = new FutureTask<>(threeWay);

            new Thread(task).start();

            System.out.println(task.get());

        } catch (Exception e) {
            e.printStackTrace();
        }

        FutureTask futureTask = new FutureTask(() -> {
            System.out.println("123 aaaaaaaaaaaaaaaaaa");
            Thread.sleep(1000);
            return "123 ret";
        });

        new Thread(futureTask).start();
        try {
            Object o = futureTask.get();
            System.out.println(o.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //four way
        Callable<Object> fourWay = Executors.callable((PrivilegedAction<?>) () -> {
            System.out.println("four way");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "four way ret";
        });

        FutureTask task = new FutureTask(fourWay);
        new Thread(task).start();
        try {
            System.out.println(task.get());
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("main end");

    }


}

class OneWay extends Thread {

    @Override
    public void run() {
        System.out.println("one way");
    }
}

class TwoWay implements Runnable {

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("two way");
    }
}

class ThreeWay implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("three way");
        return "three result";
    }
}
